#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""  
@Project : tools-for-internet-security
@File : mail_sender.py
@Author : Misha
@Time : 2025/5/12 20:48  
@脚本说明 : 邮件发送模块
"""
import yagmail
from bs4 import BeautifulSoup
import json
import smtplib
import socket
from typing import List


def get_password(json_dict, user):
    if user in json_dict:
        return json_dict[user]
    else:
        print(f"{user} 密码未保存，请使用 -p 指定密码")
        exit(1)


def send_mail(info_dict, mail_content, receiver_list: List[str],
              smtp_server, sender_email, sender_password=None, smtp_port=465):
    if not sender_password:
        sender_password = get_password(info_dict, sender_email)

    # 实例化SMTP连接
    yag = yagmail.SMTP(
        user=sender_email,
        password=sender_password,
        host=smtp_server,
        port=smtp_port,
        timeout=5,
    )

    # 获取邮件内容
    try:
        soup = BeautifulSoup(mail_content, "html.parser")
        subject = soup.find(id="subject").text
        content = str(soup.find(id="body"))
    except AttributeError:
        print("[-] 邮件内容解析失败，请参考邮件模板进行填写")
        return
    except Exception as e:
        print(f"邮件内容解析异常: {e}")
        return

    # 发送邮件
    for receiver_email in receiver_list:
        try:
            yag.send(to=receiver_email, subject=subject, contents=content)
            print(f"[+] 向 {receiver_email} 发送邮件成功")
            info_dict[f"{sender_email}"] = sender_password
            with open(".info.json", "w") as file:
                file.write(json.dumps(info_dict))
        except yagmail.error.YagInvalidEmailAddress:
            print(f"[-] {receiver_email} 邮箱格式非法")
            continue
        except smtplib.SMTPDataError:
            print(f"[-] 向 {receiver_email} 发送邮件失败，请检查是否正确")
            continue
        except smtplib.SMTPServerDisconnected:
            print("[-] 邮件发送失败，请检查发件邮箱账号/密码是否正确")
            return
        except (socket.timeout, TimeoutError):
            print("[-] 邮件发送失败，请检查网络或是否正常/服务器地址是否正确")
            return
        except Exception as e:
            print(f"邮件发送异常: {type(e)}:{e}")
            continue
        finally:
            yag.close()
